<template>
  <!-- 浇注机示意图表单弹窗 -->
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="800px"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="160"
      >
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div>
          <el-row>
            <el-col :span="24">
              <el-form-item label="计划时间" prop="planTime">
                <el-date-picker
                  v-if="!props.isReadonly"
                  v-model="formData.planTime"
                  type="datetime"
                  placeholder="请选择计划时间"
                  style="width: 100%"
                />
                <span v-else>{{ formData.planTime }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
        <el-card shadow="never" class="table-container">
          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                label="序号"
                props="machineIndex"
                min-width="50"
                align="center"
              >
                <template #default="{ $index, row }">
                  {{ row.machineIndex }}
                </template>
              </el-table-column>
              <el-table-column
                label="产品"
                props="productId"
                min-width="150"
                align="center"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    v-if="!props.isReadonly"
                    :prop="'details.' + $index + '.productId'"
                    :rules="rules.sonproductId"
                    label-width="0"
                  >
                    <el-input
                      v-model="row.productCode"
                      placeholder="请选择成品物料"
                      clearable
                      readonly
                      style="width: 100%"
                      @click="showWorkOrderSelect(row)"
                    >
                      <template #append>
                        <el-button
                          type="success"
                          plain
                          @click="showWorkOrderSelect(row)"
                          >选择</el-button
                        >
                      </template>
                    </el-input>
                  </el-form-item>
                  <span v-else>{{ row.productCode }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="产品名称"
                props="productName"
                min-width="150"
                align="center"
              >
                <template #default="{ $index, row }">
                  {{ row.productName }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <product-select
      :visible="productDialogSelect.visible"
      @change-visible="changeProductVisible"
      :materialType="3"
      :backList="productBackList"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import CommonProductSelect from "@/views/mes/lineBi/common/commonProductSelect.vue";
import { range } from "lodash-es"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESBIPRODUCTLINEDATA8ADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    formData.details = range(0, 8).map((item: any) => ({
      id: "",
      productId: "",
      productCode: "",
      productName: "",
      machineIndex: item + 1,
    }));
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  planTime: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  details: [
    {
      id: "",
      dataId: "",
      productId: "",
      productCode: "",
      productName: "",
      machineIndex: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  planTime: [{ required: true, message: "请选择计划时间", trigger: "blur" }],
  sondataId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonproductId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonproductCode: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonproductName: [
    { min: 1, max: 90, message: "长度在 1 到 90 个字符", trigger: "blur" },
  ],
  sonmachineIndex: [],
});

const isValidated = ref(false);

const details = {
  id: "",
  dataId: "",
  productId: "",
  productCode: "",
  productName: "",
  machineIndex: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.planTime = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 浇注机示意图保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/mes/biproductlinedata8/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/mes/biproductlinedata8/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}
//选择成品弹窗
const productDialogSelect = ref({
  visible: false,
});
const rowData = ref({});
const changeProductVisible = (val: boolean, data: any) => {
  productDialogSelect.value.visible = val;
  if (data) {
    rowData.value.productId = data.id;
    rowData.value.productName = data.materialName;
    rowData.value.productCode = data.materialCode;
  }
};
// 回显的数据
const productBackList = ref([]);
const showWorkOrderSelect = (row) => {
  productDialogSelect.value.visible = true;
  rowData.value = row;
};
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}
:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}
:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
</style>
